//
//  FileCacheTool.swift
//  ANOASTORE
//
//  Created by hudan on 2025/5/20.
//  Copyright © 2025 zwb. All rights reserved.
//

import Foundation
import Photos

struct FileCacheTool {
    
    /// 文件写入磁盘 (图片,视频,pdf)
    static func saveFile(fileData: Data?, fileName: String) {
        if let data = fileData {
            let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            let fileURL = documentsDirectory.appendingPathComponent(fileName)
            do {
                try data.write(to: fileURL)
            } catch {
                print("写入视频到沙盒失败: \(error)")
            }
        }
    }
    
    /// 从沙盒里取图片
    static func getImage(fileName: String) -> UIImage? {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        return UIImage(contentsOfFile: fileURL.absoluteString)
    }
    
  
    /// 获取沙盒视频的封面图片
    static func getVideoThumbnail(fileName: String) -> UIImage? {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        let asset = AVAsset(url: fileURL)
        let imageGenerator = AVAssetImageGenerator(asset: asset)
        imageGenerator.appliesPreferredTrackTransform = true
        let time = CMTime(seconds: 0, preferredTimescale: 600)
        do {
            let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
            return UIImage(cgImage: cgImage)
        } catch {
            print("获取视频封面失败: \(error)")
            return nil
        }
    }
    
    /// 去除文件名的下划线, 影响切片文件的文件名
    /// 返回格式化好的文件名和后缀和服务端切片文件夹名
    static func formatFileName(name: String) -> (String, String, String) {
        if name.count == 0 {
            return ("", "", "")
        }
        
        let arr1 = name.components(separatedBy: ".")
        
        if arr1.count == 2 {
            
            let suffix = ".\(arr1.last!)"
            
            let timeInterval: TimeInterval = Date().timeIntervalSince1970*1000
            let millisecond = CLongLong(round(timeInterval*1000))
            let folderName = "\(millisecond)"
            
            // 只有图片和视频才会修改文件名, 其他文件需要保留原文件名
            if arr1.last == "mp4" || arr1.last == "jpg" {
                // 获取毫秒级的时间作为文件名
                let fName = folderName
                return (fName, suffix, folderName)
            } else {
                // 去除下划线, 因为切片上传的接口不支持多个下划线
                var fName = arr1.first!
                // 转码
                if let decodeName = fName.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) {
                    fName = decodeName
                } else {
                    fName = folderName
                }
                
                fName = fName.replace(old: "_", str: "-")
                
                return (fName, suffix, folderName)
            }
        }
        
        return ("", "", "")
    }
}
